package gui;

import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class TableContainer extends JScrollPane
{
	private JTable table;
	
	private TableModel tableModel;
	
	private Runnable selectRowHandler;
	
	public TableContainer()
	{
		table = new JTable();
		table.setFocusable(false);
		table.setAutoCreateRowSorter(true);
		table.setShowVerticalLines(false);
		table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.addMouseListener(mouseListener);
		
		add(table);
		
		setViewportView(table);
		
		tableModel = new TableModel();
		table.setModel(tableModel);
	}
	
	public TableContainer(String[] columns, Object[][] rows)
	{
		this();
		
		tableModel.setData(columns, rows);
	}
	
	public JTable getTable()
	{
		return table;
	}
	
	public TableModel getModel()
	{
		return tableModel;
	}
	
	public void addListSelectionListener(ListSelectionListener listener)
	{
		table.getSelectionModel().addListSelectionListener(listener);
	}
	
	public Object getSelectedItem()
	{
		return tableModel.getRowSource(table.getSelectedRow());
	}
	
	public void setSelectRowHandler(Runnable handler)
	{
		this.selectRowHandler = handler;
	}
	
	private MouseListener mouseListener = new MouseAdapter()
	{
		public void mouseReleased(MouseEvent e)
		{
			if (e.getClickCount() >= 2)
			{
				selectRowHandler.run();
			}
		}
	};
}